package com.fancy.learncenter.activity;

import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.activity.base.BaseActivity;
import com.fancy.learncenter.adapter.PingLunAdapter;
import com.fancy.learncenter.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.adapter.base.CustomViewHold;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.bean.CommentsDataBean;
import com.fancy.learncenter.bean.TopDataBean;
import com.fancy.learncenter.bean.TzDetailDataBean;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.utils.WXShareUtil;
import com.fancy.learncenter.view.PopupWindowSendDiscuss;
import com.journeyapps.barcodescanner.Util;
import com.superservice.lya.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by LeeBoo on 2018/1/22.
 * <p>
 * 问答详情
 */

public class ToothDetailsActivity extends BaseActivity {

    ArrayList<String> mData;


    SimpleDraweeView user_icon;
    TextView name;
    TextView time;
    TextView tz_title;
    TextView praise_num;
    TextView praise_bt;
    TextView content;
    TextView discuss_num;
    TextView view_num;
    TextView answer_num;
    RecyclerView pic_recycleView;

    @Bind(R.id.recycleView)
    RecyclerView recycleView;

    String caseId;
    @Bind(R.id.shoucang_icon)
    ImageView shoucangIcon;


    String solve_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yayiquan_details, getResources().getColor(R.color.toolbar_color));
        ButterKnife.bind(this);

        initToolbar("问答");

        caseId = getIntent().getStringExtra("wdListDataBean");

        solve_id = getIntent().getStringExtra("solve_id");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        getWidth();

        initView();

        wdCommenLists();

        popupWindowSendDiscuss = new PopupWindowSendDiscuss(this, recycleView);

        popupWindowSendDiscuss.setSendDisCallBack(new PopupWindowSendDiscuss.SendDisCallBack() {
            @Override
            public void sendDiscuss() {


                if (Utils.isFastClick()) {
                    if (discussTz) {
                        wDComment();
                    } else {
                        wDCommentReply();
                    }
                }

            }
        });

        getData();
    }

    List<CommentsDataBean> listDataBean = new ArrayList<>();

    PopupWindowSendDiscuss popupWindowSendDiscuss;

    ImageView zan;
    ImageView wx;
    ImageView wx_friend;
    String shareUrlPic = "";
    String shareTitle = "";
    String shareContent = "";
    String shareLinkUrl = "";
    int width = 0;

    private void getWidth() {
        Resources resources = this.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        float density = dm.density;
        width = dm.widthPixels;
    }

    private void initView() {
        View headerView = LayoutInflater.from(this).inflate(R.layout.header_jinhuatie, null);
        headerView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        user_icon = (SimpleDraweeView) headerView.findViewById(R.id.user_icon);
        user_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ToothDetailsActivity.this, PersonInfoActivity.class);
                intent.putExtra("userId", "" + user_id);
                ToothDetailsActivity.this.startActivity(intent);
            }
        });

        tz_title = (TextView) headerView.findViewById(R.id.tz_title);

        name = (TextView) headerView.findViewById(R.id.name);
        view_num = (TextView) headerView.findViewById(R.id.view_num);
        discuss_num = (TextView) headerView.findViewById(R.id.discuss_num);

        answer_num = (TextView) headerView.findViewById(R.id.answer_num);

        zan = headerView.findViewById(R.id.temp);
        zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                top();
            }
        });

        wx_friend = headerView.findViewById(R.id.wx_friend);
        wx_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareUtil.getInstance(ToothDetailsActivity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, true);
            }
        });

        wx = headerView.findViewById(R.id.wx);
        wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WXShareUtil.getInstance(ToothDetailsActivity.this).shareWebPage(shareUrlPic, shareTitle, shareContent, shareLinkUrl, false);
            }
        });


        time = (TextView) headerView.findViewById(R.id.time);

        praise_num = (TextView) headerView.findViewById(R.id.praise_num);


        praise_bt = (TextView) headerView.findViewById(R.id.praise_bt);
        praise_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mfollow) {
                    cancelFollow();
                } else {
                    doFollow();
                }

            }
        });


        content = (TextView) headerView.findViewById(R.id.content);


        pic_recycleView = (RecyclerView) headerView.findViewById(R.id.pic_recycleView);

        initRecycle(headerView);


    }

    int topNum = 0;

    private void top() {
        Map map = new HashMap();
        map.put("caseId", caseId + "");

        HttpMehtod.getInstance().wdTop(map, new IdeaObserver<BaseDataBean<TopDataBean>>(this, true) {


            @Override
            public void onSuccess(BaseDataBean<TopDataBean> topDataBeanBaseDataBean) {

                String status = topDataBeanBaseDataBean.getData().getStatus();
                if (status.equals("top")) {
                    topNum++;
                    praise_num.setText(topNum + "");
                    zan.setImageResource(R.mipmap.ic_zan_s);
                } else {
                    topNum--;
                    praise_num.setText(topNum + "");
                    zan.setImageResource(R.mipmap.ic_zan);
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }


    PingLunAdapter adapter;

    private void initRecycle(View view) {
        ArrayList mData = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(linearLayoutManager);
        adapter = new PingLunAdapter(this, mData, true);
        recycleView.setAdapter(adapter);
        adapter.setHeaderView(view, recycleView);


        adapter.setOnClickCallBack(new PingLunAdapter.OnClickCallBack() {
            @Override
            public void OnClick(int position) {
                discussTz = false;

                commentId = listDataBean.get(position).getId();

                popupWindowSendDiscuss.showPop();
            }
        });


        adapter.setSolveOnClickCallBack(new PingLunAdapter.SolveOnClickCallBack() {
            @Override
            public void solveOnClick(int position) {

                if (user_id.equals(MyApplication.userId)) {
                    solve(listDataBean.get(position).getId());
                }

            }
        });


    }


    private boolean discussTz = true;

    private String commentId;


    private void wDComment() {
        Map map = new HashMap();
        map.put("caseId", caseId);
        map.put("content", popupWindowSendDiscuss.getDiscuss());

        HttpMehtod.getInstance().wDComment(map, new IdeaObserver<BaseDataBean>() {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {
                wdCommenLists();

                ToastUtil.show("评论成功");
                popupWindowSendDiscuss.dismiss();


            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void solve(final String commentId) {
        Map map = new HashMap();
        map.put("caseId", caseId);
        map.put("commentId", commentId);

        HttpMehtod.getInstance().doSolve(map, new IdeaObserver<BaseDataBean>() {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {
                ToastUtil.show("采纳成功");

                solve_id = commentId;

                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void wDCommentReply() {
        Map map = new HashMap();
        map.put("caseId", caseId);
        map.put("content", popupWindowSendDiscuss.getDiscuss());
        map.put("commentId", commentId);

        HttpMehtod.getInstance().wDCommentReply(map, new IdeaObserver() {
            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {

                ToastUtil.show("评论成功");
                popupWindowSendDiscuss.dismiss();
                popupWindowSendDiscuss.getDiscuss();
                wdCommenLists();
            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void wdCommenLists() {
        Map map = new HashMap();
        map.put("caseId", caseId + "");

        HttpMehtod.getInstance().wdCommenLists(map, new IdeaObserver<BaseDataBean<List<CommentsDataBean>>>() {

            @Override
            public void onSuccess(BaseDataBean<List<CommentsDataBean>> listBaseDataBean) {

                if (listBaseDataBean.getData() != null) {


                    if (!TextUtils.isEmpty(solve_id)) {
                        for (int i = 0; i < listBaseDataBean.getData().size(); i++) {

                            if (solve_id.equals(listBaseDataBean.getData().get(i).getId())) {
                                listBaseDataBean.getData().get(i).setStatus("1");
                            }

                        }
                    }


                    listDataBean = listBaseDataBean.getData();
                    adapter.notifyDataSetChanged((ArrayList<CommentsDataBean>) listBaseDataBean.getData());

                    answer_num.setText("回帖列表(" + listBaseDataBean.getData().size() + ")");
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }


    //未关注
    boolean mfollow = false;

    private void doFollow() {
        Map map = new HashMap();
        map.put("tUserId", user_id);

        HttpMehtod.getInstance().doFollow(map, new IdeaObserver<BaseDataBean>(this, true) {

            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {
                mfollow = true;
                praise_bt.setText("-已关注");
                praise_bt.setBackgroundResource(R.drawable.follow_cancer_bg);

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    private void cancelFollow() {
        Map map = new HashMap();
        map.put("tUserId", user_id);

        HttpMehtod.getInstance().cancelFollow(map, new IdeaObserver<BaseDataBean>(this, true) {

            @Override
            public void onSuccess(BaseDataBean listBaseDataBean) {
                mfollow = false;
                praise_bt.setText("+关注");
                praise_bt.setBackgroundResource(R.drawable.follow_bg);

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }

    boolean mCollect = false;

    private void collect() {
        Map map = new HashMap();
        map.put("relationId", caseId + "");
        map.put("type", "4");
        HttpMehtod.getInstance().collect(map, new IdeaObserver<BaseDataBean>() {


            @Override
            public void onSuccess(BaseDataBean baseDataBean) {
                mCollect = true;
                shoucangIcon.setImageResource(R.mipmap.ic_shoucangdown);
            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }

    private void cancelCollect() {
        Map map = new HashMap();
        map.put("relationId", caseId + "");
        map.put("type", "4");

        HttpMehtod.getInstance().cancelCollect(map, new IdeaObserver<BaseDataBean>() {


            @Override
            public void onSuccess(BaseDataBean baseDataBean) {
                mCollect = false;
                shoucangIcon.setImageResource(R.mipmap.ic_shoucang_gray);
            }

            @Override
            public void onFail(int errorCode) {

            }
        });

    }


    String user_id;

    private void getData() {
        Map map = new HashMap();
        map.put("caseId", caseId);

        HttpMehtod.getInstance().wDDetail(map, new IdeaObserver<BaseDataBean<TzDetailDataBean>>() {


            @Override
            public void onSuccess(BaseDataBean<TzDetailDataBean> tzDetailDataBeanBaseDataBean) {

                final TzDetailDataBean wdListDataBean = tzDetailDataBeanBaseDataBean.getData();


                shareUrlPic = tzDetailDataBeanBaseDataBean.getData().getShare_img();
                shareContent = tzDetailDataBeanBaseDataBean.getData().getShare_content();
                shareLinkUrl = tzDetailDataBeanBaseDataBean.getData().getShare_link();
                shareTitle = tzDetailDataBeanBaseDataBean.getData().getShare_title();

                user_icon.setImageURI(tzDetailDataBeanBaseDataBean.getData().getImgsrc());
                tz_title.setText(tzDetailDataBeanBaseDataBean.getData().getTitle());
                name.setText(tzDetailDataBeanBaseDataBean.getData().getUser_name());
                time.setText(tzDetailDataBeanBaseDataBean.getData().getAdd_time());

                user_id = tzDetailDataBeanBaseDataBean.getData().getUser_id();

                content.setText(wdListDataBean.getContent());
                praise_num.setText(wdListDataBean.getTop_num() + "");
                topNum = wdListDataBean.getTop_num();
                time.setText(wdListDataBean.getAdd_time());
                tz_title.setText(wdListDataBean.getTitle());
                name.setText(wdListDataBean.getUser_name());
                user_icon.setImageURI(wdListDataBean.getImgsrc());


                discuss_num.setText(wdListDataBean.getComment_num() + "回帖");

                view_num.setText(wdListDataBean.getView_num());


                if (wdListDataBean.getImglist() != null) {
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ToothDetailsActivity.this);
                    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    pic_recycleView.setLayoutManager(linearLayoutManager);
                    pic_recycleView.setAdapter(new CommonRecycleViewAdapter<String>(ToothDetailsActivity.this, R.layout.wd_detail_pic_item, (ArrayList<String>) wdListDataBean.getImglist()) {
                        @Override
                        public void bindView(CustomViewHold customViewHold, final String item, final int position) {
                            SimpleDraweeView simpleDraweeView = customViewHold.getView(R.id.simpleDraweeView);
                            Utils.setControllerListener(simpleDraweeView, item, width);
//                            Utils.setControllerListener(simpleDraweeView, width);
//                            simpleDraweeView.setImageURI(item);

                            simpleDraweeView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(mContext, GalleryPicDetailActivity.class);
                                    intent.putStringArrayListExtra(GalleryPicDetailActivity.PIC_KEY, (ArrayList<String>) wdListDataBean.getImglist());
                                    intent.putExtra(GalleryPicDetailActivity.PIC_POSITION_KEY, position);
                                    mContext.startActivity(intent);
                                }
                            });
                        }
                    });
                }


                if (tzDetailDataBeanBaseDataBean.getData().getIs_top() == 0) {

                    zan.setImageResource(R.mipmap.ic_zan);

                } else {

                    zan.setImageResource(R.mipmap.ic_zan_s);

                }


                if (tzDetailDataBeanBaseDataBean.getData().getIs_follow() == 0) {

                    mfollow = false;
                    praise_bt.setBackgroundResource(R.drawable.follow_bg);
                    praise_bt.setText("+关注");
                } else {
                    mfollow = true;
                    praise_bt.setText("-已关注");
                    praise_bt.setBackgroundResource(R.drawable.follow_cancer_bg);

                }

                if (tzDetailDataBeanBaseDataBean.getData().getIs_collect() == 0) {
                    mCollect = false;
                    shoucangIcon.setImageResource(R.mipmap.ic_shoucang_gray);
                } else {
                    mCollect = true;
                    shoucangIcon.setImageResource(R.mipmap.ic_shoucangdown);
                }

            }

            @Override
            public void onFail(int errorCode) {

            }
        });
    }


    @OnClick({R.id.shoucang, R.id.sub_discuss})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.shoucang:

                if (mCollect) {
                    cancelCollect();
                } else {
                    collect();
                }

                break;
            case R.id.sub_discuss:
                discussTz = true;
                popupWindowSendDiscuss.showPop();
                break;
        }
    }
}
